package org.wedding.center.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.commons.lang.StringUtils;
import org.wedding.center.entity.OrderInfo;
import org.wedding.dto.PageModel;
import org.wedding.center.dto.query.CouponQuery;
import org.wedding.center.entity.CouponInfo;
import org.wedding.center.mapper.CouponInfoMapper;
import org.wedding.center.service.CouponInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.wedding.enums.system.ResultCodeEnum;
import org.wedding.system.entity.UserInfo;
import org.wedding.system.mapper.UserMapper;
import org.wedding.utils.CommonResult;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import org.springframework.stereotype.Service;
import cn.hutool.core.util.ObjectUtil;
import org.wedding.utils.PageUtil;
import org.wedding.utils.RedisUtil;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 优惠卷信息表(CouponInfo)表服务实现类
 *
 * @author songkaiyue
 * @since 2025-05-19 17:26:18
 */
@Service
public class CouponInfoServiceImpl extends ServiceImpl<CouponInfoMapper, CouponInfo> implements CouponInfoService {
    private final UserMapper userMapper;
    @Resource
    private RedisUtil redisUtil;

    public CouponInfoServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    /**
     * 分页查询所有数据
     * @return
     */
    @Override
    public CommonResult<PageModel> findAll(CouponQuery query) {
        try {
            List<CouponInfo> list = baseMapper.selectAll(query);
            for (CouponInfo couponInfo : list) {
                if(StrUtil.isNotEmpty(couponInfo.getUserId())){
                    UserInfo userInfo = userMapper.findById(couponInfo.getUserId());
                    couponInfo.setUserName(userInfo.getUserName());
                }
            }
            List<CouponInfo> setList = query.setList(PageUtil.getListPage(query.getCurrent(), query.getPageSize(), list), list.size());
            query.setList(setList, list.size());
            return CommonResult.success(query);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }

    }


    @Override
    public void addYhq(String userId) {
            CouponQuery query = new CouponQuery();
            query.setType("0");
            List<CouponInfo> list = baseMapper.selectAll(query);
            for (CouponInfo couponInfo : list) {
                CouponInfo  couponInfonew = new CouponInfo();
                couponInfonew.setId(IdUtil.simpleUUID());
                couponInfonew.setCreateTime(DateUtil.now());
                couponInfonew.setDelFlag("0");
                couponInfonew.setStatus("0");
                couponInfonew.setType("1");
                couponInfonew.setIsUse("0");
                couponInfo.setUserId(userId);
                couponInfo.setAmount(couponInfo.getAmount());
                couponInfo.setLimitTime(couponInfo.getLimitTime());
                baseMapper.insert(couponInfo);
            }



    }

    /**
     * 根据id查看详情
     *
     * @param id
     * @return
     */
    @Override
    public CommonResult<CouponInfo> view(String id) {
        try {
            CouponInfo couponInfo = baseMapper.findById(id);
            return CommonResult.success(couponInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

    /**
     * 更新已过期优惠券
     * @return
     */
    @Override
    public CommonResult expired() {
        try {
            String userId = StpUtil.getSession().get("userId").toString();
            baseMapper.updateExpired(userId);
            return CommonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

    @Override
    public CommonResult expiredById(String id) {
        try {
            baseMapper.updateExpiredById(id);
            return CommonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

    /**
     * 新增数据
     *
     * @param couponInfo
     * @return
     */
    @Override
    public CommonResult add(CouponInfo couponInfo) {
        try {
            couponInfo.setId(IdUtil.simpleUUID());
            couponInfo.setCreateTime(DateUtil.now());
            couponInfo.setDelFlag("0");
            couponInfo.setStatus("0");
            couponInfo.setIsUse("0");
            if(StringUtils.isEmpty(couponInfo.getUserId())){
                String userId = StpUtil.getSession().get("userId").toString();
                couponInfo.setUserId(userId);
            }
            if (ObjectUtil.isNotEmpty(couponInfo.getValidityDay())){
                //计算到期时间
                String limitTime = DateUtil.offsetDay(DateUtil.date(),couponInfo.getValidityDay()).toString();
                couponInfo.setLimitTime(limitTime);
                //储存redis-用于监听优惠卷过期时间并在过期后进行状态更新
                redisUtil.setValueByTime("coupon:"+couponInfo.getId(),couponInfo.getId(), couponInfo.getValidityDay(), TimeUnit.DAYS);
            }
            baseMapper.insert(couponInfo);
            return CommonResult.success(couponInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

    /**
     * 使用优惠券
     * @param orderInfo
     * @return
     */
    @Override
    public CommonResult<CouponInfo> useCoupon(OrderInfo orderInfo) {
        try {
            CouponInfo couponInfo = baseMapper.findById(orderInfo.getCouponId());
            couponInfo.setOrderId(orderInfo.getId());
            couponInfo.setOrderCode(orderInfo.getCode());
            couponInfo.setStatus("1");
            baseMapper.updateById(couponInfo);
            return CommonResult.success(couponInfo);
        }catch (Exception e){
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

    /**
     * 修改数据
     *
     * @param couponInfo
     * @return
     */
    @Override
    public CommonResult updateEntity(CouponInfo couponInfo) {
        try {
            if (ObjectUtil.isNotEmpty(couponInfo.getValidityDay())){
                //计算到期时间
                String limitTime = DateUtil.offsetDay(DateUtil.date(),couponInfo.getValidityDay()).toString();
                couponInfo.setLimitTime(limitTime);
            }
            couponInfo.setUpdateTime(DateUtil.now());
            baseMapper.updateById(couponInfo);
            return CommonResult.success(couponInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

      /**
     * 删除数据
     *
     * @param ids
     * @return
     */
    @Override
    public CommonResult delete(List<String> ids) {
        try {
            if (ObjectUtil.isEmpty(ids)) return CommonResult.failed(ResultCodeEnum.PARAM_ERROR);
            for (String id : ids) {
                baseMapper.upDeleteById(id);
            }
            return CommonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

    @Override
    public List<CouponInfo> findByUseType() {
        try {
            return baseMapper.findByUseType();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
